package com.imooc.controller;

import com.imooc.common.utils.ResultVoUtil;
import com.imooc.common.vo.ProductInfoVo;
import com.imooc.common.vo.ProductVo;
import com.imooc.common.vo.ResultVo;
import com.imooc.dataobject.ProductCategory;
import com.imooc.dataobject.ProductInfo;
import com.imooc.service.CategoryService;
import com.imooc.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    ProductService productService;

    @Autowired
    CategoryService categoryService;

    @RequestMapping("/list")
    public ResultVo list() {
        // 1.查询所有上架商品
        List<ProductInfo> productInfoList = productService.findUpAll();
        log.info("上架商品：{}", productInfoList);

        // 2.查询类目
        List<Integer> categoryTypeList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        log.info("商品类目：{}", productCategoryList);

        List<ProductVo> productVoList = new ArrayList();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVo productVo = new ProductVo();
            BeanUtils.copyProperties(productCategory, productVo);
            List<ProductInfoVo> list = new ArrayList();
            for (ProductInfo productInfo : productInfoList) {
                ProductInfoVo productInfoVo = new ProductInfoVo();
                if (Objects.equals(productCategory.getCategoryType(), productInfo.getCategoryType())) {
                    BeanUtils.copyProperties(productInfo, productInfoVo);
                    list.add(productInfoVo);
                }
            }
            productVo.setProductInfoVoList(list);
            productVoList.add(productVo);
        }

        return ResultVoUtil.success(productVoList);
    }
}
